#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
快速搜索工具 - 在MongoDB中搜索房型数据
"""

import sys
from pymongo import MongoClient
from config import ROOM_MONGODB_CONFIG
import json

def search_by_id(_id: str):
    """按_id搜索"""
    client = MongoClient(
        host=ROOM_MONGODB_CONFIG['host'],
        port=ROOM_MONGODB_CONFIG['port'],
        username=ROOM_MONGODB_CONFIG['username'],
        password=ROOM_MONGODB_CONFIG['password']
    )
    
    db = client[ROOM_MONGODB_CONFIG['db_name']]
    collection = db[ROOM_MONGODB_CONFIG['collection_name']]
    
    doc = collection.find_one({'_id': _id})
    
    if doc:
        print("\n" + "=" * 70)
        print(f"找到数据！_id = {_id}")
        print("=" * 70)
        print(f"房型ID: {doc.get('roomId')}")
        print(f"房型名称: {doc.get('roomName')}")
        print(f"酒店ID: {doc.get('hotelId')}")
        print(f"\n完整数据（JSON格式）:")
        print(json.dumps(doc, indent=2, ensure_ascii=False, default=str))
    else:
        print(f"\n未找到 _id = {_id} 的数据")
    
    client.close()

def search_by_room_id(room_id: str):
    """按roomId搜索"""
    client = MongoClient(
        host=ROOM_MONGODB_CONFIG['host'],
        port=ROOM_MONGODB_CONFIG['port'],
        username=ROOM_MONGODB_CONFIG['username'],
        password=ROOM_MONGODB_CONFIG['password']
    )
    
    db = client[ROOM_MONGODB_CONFIG['db_name']]
    collection = db[ROOM_MONGODB_CONFIG['collection_name']]
    
    # 尝试整数查询
    try:
        room_id_int = int(room_id)
        docs = list(collection.find({'roomId': room_id_int}).limit(5))
        
        if docs:
            print("\n" + "=" * 70)
            print(f"找到 {len(docs)} 条数据！roomId = {room_id_int}")
            print("=" * 70)
            for i, doc in enumerate(docs, 1):
                print(f"\n[{i}] _id: {doc.get('_id')}")
                print(f"    房型名称: {doc.get('roomName')}")
                print(f"    酒店ID: {doc.get('hotelId')}")
        else:
            print(f"\n未找到 roomId = {room_id} 的数据")
    except ValueError:
        print(f"\n错误：roomId必须是数字")
    
    client.close()

def main():
    """主函数"""
    if len(sys.argv) < 3:
        print("\n使用方法:")
        print("  python quick_search.py _id <ID值>")
        print("  python quick_search.py roomid <房型ID>")
        print("\n示例:")
        print("  python quick_search.py _id 10000034_49564431")
        print("  python quick_search.py roomid 49564431")
        return
    
    search_type = sys.argv[1].lower()
    search_value = sys.argv[2]
    
    if search_type == '_id':
        search_by_id(search_value)
    elif search_type == 'roomid':
        search_by_room_id(search_value)
    else:
        print(f"\n错误：不支持的搜索类型 '{search_type}'")
        print("支持的类型：_id, roomid")

if __name__ == '__main__':
    main()

